package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.function.MyAsyncFunction;
import com.danan.realtime.pojo.TradeTrademarkCategoryUserRefundBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import com.ibm.icu.text.NumberFormat;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
public class DwsApp_11_trade_trademark_category_user_refund_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_11_trade_trademark_category_user_refund_window().init(
                5011,
                3,
                "DwsApp_11_trade_trademark_category_user_refund_window",
                Constant.TOPIC_DWD_TRADE_ORDER_REFUND
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 封装为pojo
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanDs = toTradeTrademarkCategoryUserRefundBean(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> aggDs = windowAndAgg(beanDs);
        // 3 扩展维度信息
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> resultDs = extendDimConfig(aggDs);
        // 4 将结果写入Clickhouse
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_TRADE_TRADEMARK_CATEGORY_USER_REFUND_WINDOW,TradeTrademarkCategoryUserRefundBean.class));
    }

    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> extendDimConfig(SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> ds) {
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> skuInfoDs = AsyncDataStream.unorderedWait(
                ds,
                new MyAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public String getTable() {
                        return "dim_sku_info";
                    }

                    @Override
                    public String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getSkuId();
                    }

                    @Override
                    protected void extendDimInfo(TradeTrademarkCategoryUserRefundBean data, JSONObject dimInfo) {
                        data.setCategory3Id(dimInfo.getString("CATEGORY3_ID"));
                        data.setTrademarkId(dimInfo.getString("TM_ID"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> tmInfoDs = AsyncDataStream.unorderedWait(
                skuInfoDs,
                new MyAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public String getTable() {
                        return "dim_base_trademark";
                    }

                    @Override
                    public String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getTrademarkId();
                    }

                    @Override
                    protected void extendDimInfo(TradeTrademarkCategoryUserRefundBean data, JSONObject dimInfo) {
                        data.setTrademarkName(dimInfo.getString("TM_NAME"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> c3InfoDs = AsyncDataStream.unorderedWait(
                tmInfoDs,
                new MyAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public String getTable() {
                        return "dim_base_category3";
                    }

                    @Override
                    public String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getCategory3Id();
                    }

                    @Override
                    protected void extendDimInfo(TradeTrademarkCategoryUserRefundBean data, JSONObject dimInfo) {
                        data.setCategory3Name(dimInfo.getString("NAME"));
                        data.setCategory2Id(dimInfo.getString("CATEGORY2_ID"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> c2InfoDs = AsyncDataStream.unorderedWait(
                c3InfoDs,
                new MyAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public String getTable() {
                        return "dim_base_category2";
                    }

                    @Override
                    public String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getCategory2Id();
                    }

                    @Override
                    protected void extendDimInfo(TradeTrademarkCategoryUserRefundBean data, JSONObject dimInfo) {
                        data.setCategory2Name(dimInfo.getString("NAME"));
                        data.setCategory1Id(dimInfo.getString("CATEGORY1_ID"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );

        return AsyncDataStream.unorderedWait(
                c2InfoDs,
                new MyAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public String getTable() {
                        return "dim_base_category1";
                    }

                    @Override
                    public String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getCategory1Id();
                    }

                    @Override
                    protected void extendDimInfo(TradeTrademarkCategoryUserRefundBean data, JSONObject dimInfo) {
                        data.setCategory1Name(dimInfo.getString("NAME"));
                    }
                },
                120,
                TimeUnit.SECONDS
        );
    }

    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> windowAndAgg(SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> ds) {
        // 创建水印策略
        WatermarkStrategy<TradeTrademarkCategoryUserRefundBean> strategy = WatermarkStrategy.<TradeTrademarkCategoryUserRefundBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .keyBy(t -> t.getSkuId() + "_" + t.getUserId())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean reduce(TradeTrademarkCategoryUserRefundBean t1, TradeTrademarkCategoryUserRefundBean t2) throws Exception {
                        t2.getIds().addAll(t1.getIds());
                        return t2;
                    }
                }, new WindowFunction<TradeTrademarkCategoryUserRefundBean, TradeTrademarkCategoryUserRefundBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TradeTrademarkCategoryUserRefundBean> input, Collector<TradeTrademarkCategoryUserRefundBean> out) throws Exception {
                        TradeTrademarkCategoryUserRefundBean result = input.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setRefundCount((long) result.getIds().size());
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> toTradeTrademarkCategoryUserRefundBean(DataStreamSource<String> ds) {
        return ds.map(JSON::parseObject)
                .filter(j -> j.getString("user_id") != null)
                .map(new RichMapFunction<JSONObject, TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean map(JSONObject j) throws Exception {
                        HashSet<String> ids = new HashSet<>();
                        String userId = j.getString("order_id");
                        ids.add(userId);
                        return TradeTrademarkCategoryUserRefundBean.builder()
                                .skuId(j.getString("sku_id"))
                                .userId(userId)
                                .ids(ids)
                                .ts(j.getLong("ts") * 1000)
                                .build();
                    }
                });
    }
}
